//
//  RBBindPhoneController.m
//  MaterialXBUser
//
//  Created by XBWH on 2024/3/6.
//

#import "RBBindPhoneController.h"
#import "RBTimerCountDown.h"
#import "RBGenerateUserSigIn.h"
#import "AppDelegate.h"

@interface RBBindPhoneController ()<UITextFieldDelegate>
@property(strong,nonatomic)UILabel *rbThemeLabel;
@property(strong,nonatomic)UILabel *rbThemeSecordLabel;
@property(strong,nonatomic)UITextField *rbAccountTf;
@property(strong,nonatomic)UITextField *rbCodeAuthTf;
@property(strong,nonatomic)UIButton *rbAuthCodeButton;
@property(strong,nonatomic)UIView *rbLineView;
@property(strong,nonatomic)UIView *rbLineSecordView;
@property(strong,nonatomic)UIButton *rbLoginButton;
@end

@implementation RBBindPhoneController

-(void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"绑定手机号";
    self.view.backgroundColor = RBColor(255, 255, 255);
    
    [self rb_initViewUI];
}

-(void)rb_initViewUI{
    
    self.rbThemeLabel = [UILabel rb_labelWithTitle:@"首次登录需绑定手机号" color:RBColor(51, 51, 51) font:RBPingFangBlodFont(24) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbThemeLabel];
    
    self.rbThemeSecordLabel = [UILabel rb_labelWithTitle:@"为了您的账户安全，请绑定手机号" color:RBColor(153, 153, 153) font:RBPingFangMediumFont(15) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbThemeSecordLabel];
    
    self.rbAccountTf = [[UITextField alloc]init];
    self.rbAccountTf.backgroundColor = [UIColor clearColor];
    self.rbAccountTf.font = RBPingFangFont(14);
    self.rbAccountTf.textAlignment = NSTextAlignmentLeft;
    self.rbAccountTf.textColor = RBColor(51, 51, 51);
    self.rbAccountTf.delegate = self;
    [self.rbAccountTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.rbAccountTf.placeholder = @"请输入手机号";
    self.rbAccountTf.keyboardType = UIKeyboardTypePhonePad;
    self.rbAccountTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.rbAccountTf];
    
    self.rbCodeAuthTf = [[UITextField alloc]init];
    self.rbCodeAuthTf.backgroundColor = [UIColor clearColor];
    self.rbCodeAuthTf.font = RBPingFangFont(14);
    self.rbCodeAuthTf.textAlignment = NSTextAlignmentLeft;
    self.rbCodeAuthTf.textColor = RBColor(51, 51, 51);
    self.rbCodeAuthTf.delegate = self;
    [self.rbCodeAuthTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.rbCodeAuthTf.placeholder = @"请输入验证码";
    self.rbCodeAuthTf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:self.rbCodeAuthTf];
    
    self.rbAuthCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbAuthCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.rbAuthCodeButton addTarget:self action:@selector(authCodeButtonTap) forControlEvents:UIControlEventTouchUpInside];
    self.rbAuthCodeButton.titleLabel.font = RBPingFangFont(16);
    [self.rbAuthCodeButton setTitleColor:RBColor(242, 48, 48) forState:UIControlStateNormal];
    [self.view addSubview:self.rbAuthCodeButton];
    
    self.rbLineView = [[UIView alloc]init];
    self.rbLineView.backgroundColor = RBColor(237, 237, 237);
    [self.view addSubview:self.rbLineView];
    
    self.rbLineSecordView = [[UIView alloc]init];
    self.rbLineSecordView.backgroundColor = RBColor(237, 237, 237);
    [self.view addSubview:self.rbLineSecordView];
    
    self.rbLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbLoginButton setTitle:@"立即绑定" forState:UIControlStateNormal];
    [self.rbLoginButton addTarget:self action:@selector(loginButtonTap) forControlEvents:UIControlEventTouchUpInside];
    self.rbLoginButton.titleLabel.font = RBPingFangFont(16);
    [self.rbLoginButton setTitleColor:RBColor(255, 255, 255) forState:UIControlStateNormal];
    self.rbLoginButton.backgroundColor = RBColor(217, 217, 217);
    [self.view addSubview:self.rbLoginButton];
    
    [self.rbThemeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(RBScaleWidth(20));
        make.top.mas_equalTo(RBNAVIGATION_BAR_HEIGHT+RBScaleWidth(32));
        make.height.mas_equalTo(RBScaleWidth(22));
        make.width.mas_equalTo(RBScaleWidth(250));
    }];
    [self.rbThemeSecordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.rbThemeLabel.mas_left);
        make.top.mas_equalTo(self.rbThemeLabel.mas_bottom).mas_offset(RBScaleWidth(15));
        make.height.mas_equalTo(RBScaleWidth(14));
        make.width.mas_equalTo(RBScaleWidth(300));
    }];
    [self.rbAccountTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbThemeSecordLabel.mas_bottom).mas_offset(RBScaleWidth(30));
        make.left.mas_equalTo(self.rbThemeLabel.mas_left);
        make.right.mas_equalTo(-RBScaleWidth(20));
        make.height.mas_equalTo(RBScaleWidth(30));
    }];
    [self.rbLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.rbAccountTf.mas_left);
        make.right.mas_equalTo(self.rbAccountTf.mas_right);
        make.top.mas_equalTo(self.rbAccountTf.mas_bottom).mas_offset(RBScaleWidth(20));
        make.height.mas_equalTo(RBScaleWidth(0.5));
    }];
    [self.rbCodeAuthTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbLineView.mas_bottom).mas_offset(RBScaleWidth(15));
        make.left.mas_equalTo(self.rbAccountTf.mas_left);
        make.right.mas_equalTo(RBScaleWidth(150));
        make.height.mas_equalTo(RBScaleWidth(30));
    }];
    [self.rbAuthCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbCodeAuthTf.mas_top);
        make.right.mas_equalTo(self.rbLineView.mas_right);
        make.height.mas_equalTo(RBScaleWidth(30));
        make.width.mas_equalTo(RBScaleWidth(100));
    }];
    [self.rbLineSecordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.rbLineView.mas_left);
        make.right.mas_equalTo(self.rbLineView.mas_right);
        make.top.mas_equalTo(self.rbLineView.mas_bottom).mas_offset(RBScaleWidth(60));
        make.height.mas_equalTo(RBScaleWidth(0.5));
    }];
    [self.rbLoginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(RBScaleWidth(20));
        make.right.mas_equalTo(-RBScaleWidth(20));
        make.top.mas_equalTo(self.rbLineSecordView.mas_bottom).mas_offset(RBScaleWidth(40));
        make.height.mas_equalTo(RBScaleWidth(48));
    }];
    self.rbLoginButton.layer.cornerRadius = RBScaleWidth(24);
    self.rbLoginButton.layer.masksToBounds = YES;
}
#pragma mark - 响应事件
-(void)textFieldDidChange:(UITextField *)textField{
    if (textField == self.rbAccountTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    } else if (textField == self.rbCodeAuthTf){
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
        [self rb_UpdateLoginBtnState:self.rbAccountTf.text WithPwdStr:self.rbCodeAuthTf.text];
    }
}
-(void)rb_UpdateLoginBtnState:(NSString *)phoneStr WithPwdStr:(NSString *)pwdStr{
    if (phoneStr.length>0&&pwdStr.length>5) {
        self.rbLoginButton.backgroundColor = RBColor(242, 48, 48);
    }else{
        self.rbLoginButton.backgroundColor = RBColor(217, 217, 217);
    }
}
-(void)authCodeButtonTap{
    if ([RBTool rb_isEmptyStr:self.rbAccountTf.text]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入正确的手机号" ToView:RBWindow];
        return;
    }
    
    MJWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"phone"] = self.rbAccountTf.text;
    dict[@"type"] = @"0";
    dict[@"term"] = @"user";
    [RBNetworkTool GET:RBSmsURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] intValue] == 1) {
            [MBProgressHUD rb_showAutoMessage:@"验证码已发送" ToView:RBWindow];
            [weakSelf.rbAuthCodeButton setTitle:@"60秒后重试" forState:UIControlStateNormal];

            [RBTimerCountDown rb_timerWithTime:60 interval:1 changed:^(float remain) {
                [weakSelf.rbAuthCodeButton setTitle:[NSString stringWithFormat:@"%d秒后重试",(int)remain] forState:UIControlStateNormal];
            } complete:^{
                weakSelf.rbAuthCodeButton.userInteractionEnabled = YES;
                [weakSelf.rbAuthCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            }];
            [weakSelf.rbCodeAuthTf becomeFirstResponder];
            
        } else {
            weakSelf.rbAuthCodeButton.userInteractionEnabled = YES;
            [weakSelf.rbAuthCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
    } error:^(id responseObject) {
        weakSelf.rbAuthCodeButton.userInteractionEnabled = YES;
        [weakSelf.rbAuthCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    } failure:^(NSError *error) {
        weakSelf.rbAuthCodeButton.userInteractionEnabled = YES;
        [weakSelf.rbAuthCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }];
}
-(void)loginButtonTap{
    if ([RBTool rb_isEmptyStr:self.rbAccountTf.text]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入正确的手机号" ToView:RBWindow];
        return;
    }
    if ([RBTool rb_isEmptyStr:self.rbCodeAuthTf.text]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入验证码" ToView:RBWindow];
        return;
    }
    
    MJWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"phone"] = self.rbAccountTf.text;
    dict[@"code"] = self.rbCodeAuthTf.text;
    dict[@"oauthId"] = self.oauthId;
    [RBNetworkTool POST:RBBindMobileURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            NSString *token = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"token"]];
            RBUserModel *userModel = [RBUserModel mj_objectWithKeyValues:responseObject[@"result"][@"userInfo"]];
            userModel.token = token;
            if (userModel.imSecret.length==0) {
                userModel.imSecret = secretkey;
            }
            if (userModel.imAppId.length==0) {
                userModel.imAppId = [NSString stringWithFormat:@"%d",sdkappid];
            }
            
            //保存用户信息
            [RBArchiveTool rb_saveUserModel:userModel];

            [[RBLogInAndOutTool shareInstance] rb_saveLogin:userModel.userId withAppId:SDKAPPID withUserSig:[RBGenerateUserSigIn genTestUserSig:userModel.userId]];
            
            // 通知更新个人信息
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateUserInfmation" object:nil];
            // 登录成功通知刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateRefershData" object:nil];
        
            NSString *selectIndex = [NSString stringWithFormat:@"%ld",self.selectedIndex];
            NSDictionary *dict = @{
                                    @"logSelect":selectIndex,
                                    @"source":self.source?self.source:@""
                                   };
            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"RBLoginSuccess" object:nil userInfo:dict]];
            
            [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    } error:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 10077 || [responseObject[@"code"] intValue] == 10006) {
            [MBProgressHUD rb_showAutoMessage:@"此手机号已注销，请重新输入新的手机号" ToView:RBWindow];
            return;
        }
    } failure:^(NSError *error) {
    }];
}


@end
